layui.define(['form', 'layedit', 'laydate', 'xmSelect'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;
    let xmSelect = layui.xmSelect;
    let status = true;

    $("#deposit").val(json.channelPriceVO.deposit / 100)
    $("#depositDeductionAmount").val(json.channelPriceVO.depositDeductionAmount / 100)

    form.verify({
        maxSix: function (value) {
            if (zmnUtil.isNull(value) || value == "") {
            } else {
                if (status) {
                    if (!/^[0-9]+(.[0-9]{1,2})?$/.test(value)) {
                        return '请输入1-100的数字，支持两位小数!';
                    }
                    if (value > 100 || value < 1) {
                        return '请输入1-100的数字，支持两位小数!';
                    }
                }

            }
        }
    });
    zmnLayUtil.layFormVerify(form);

    // 分类下拉框联动
    zmnPage.laySelectLinkage(form, "/common/area/listChilds.action", "provinceId", "cityId", null);
    zmnPage.laySelectLinkage(form, "/common/area/listChilds.action", "provinceId1", "cityId1", null);
    form.render(null, "zmn-form");

    if (json.onePriceList !== null && json.onePriceList.length > 0) {
        json.onePriceList.forEach(function (data) {
            addCity(data.provinceId, data.cityId, data.provinceName, data.cityName, $('#addCityDiv'));
        });
    }

    if (json.basePriceList !== null && json.basePriceList.length > 0) {
        json.basePriceList.forEach(function (data) {
            addCity(data.provinceId, data.cityId, data.provinceName, data.cityName, $('#addCityDiv1'));
        });
    }

    if (zmnUtil.isNotNull(json.channelPriceVO.depositStatus)) {
        if (json.channelPriceVO.depositStatus === 2) {
            $("#depositBlock").show();
        } else {
            status = false;
        }
    }

    if (json.channelPriceVO.payType === 1) {
        $("#setDeposit").show();
        if (json.channelPriceVO.depositStatus === 2) {
            $("#depositBlock").show();
        }
    }

    $('#addCity').click(function () {

        let channelId = $('#channelId').val();
        let provinceId = $('#provinceId').val();
        if (provinceId == 0) {
            layer.alert('请选择省');
            return false;
        }
        let cityId = $('#cityId').val();
        let provinceName = $('select[name="provinceId"] option:selected').text();
        let cityName = $('select[name="cityId"] option:selected').text();
        let type = $('#type').val();
        var url = '/pilot/channel/price/checkCity';
        zmnLayUtil.ajaxSimpleUE(url, {
            provinceId: provinceId,
            cityId: cityId,
            channelId: channelId,
            type: type
        }, null, function (resp) {
            console.log(resp);
            if (resp.status == 200) {
                addCity(provinceId, cityId, provinceName, cityName, $('#addCityDiv'));
            } else {
                layer.alert(resp.message);
            }
        });

        return false;
    });

    $('#addCity1').click(function () {
        let channelId = $('#channelId').val();
        let provinceId = $('#provinceId1').val();
        if (provinceId == 0) {
            layer.alert('请选择省');
            return false;
        }
        let cityId = $('#cityId1').val();
        let provinceName = $('select[name="provinceId1"] option:selected').text();
        let cityName = $('select[name="cityId1"] option:selected').text();
        let type = $('#type').val();
        var url = '/pilot/channel/price/checkCity';
        zmnLayUtil.ajaxSimpleUE(url, {
            provinceId: provinceId,
            cityId: cityId,
            channelId: channelId,
            type: type
        }, null, function (resp) {
            console.log(resp);
            if (resp.status == 200) {
                addCity(provinceId, cityId, provinceName, cityName, $('#addCityDiv1'));
            } else {
                layer.alert(resp.message);
            }
        });

        return false;
    });

    function addCity(provinceId, cityId, provinceName, cityName, addCityDiv) {
        let flag = false;
        let checkMsg = "当前城市已存在！";

        $('.cityprice').each(function (index, obj) {
            var cityValue = $(obj).attr('value');
            var split = cityValue.split("&");
            if (cityValue == (provinceId + "&" + cityId)) {
                flag = true;
                return false;
            } else if (provinceId == split[0] && (split[1] == null || split[1] == "")) {
                checkMsg = "父级城市已存在！";
                flag = true;
                return false;
            } else if (provinceId == split[0] && (cityId == null || cityId == "")) {
                checkMsg = "子级城市已存在！";
                flag = true;
                return false;
            }
        });

        if (flag) {
            layer.alert(checkMsg);
            return;
        }

        let closeBtn = json.isDetail ? '' : '<i style="font-style: normal;margin-left: 10px;cursor: pointer;">X</i>';

        if ((provinceId == 0 || provinceId == '' || provinceId == null) && (cityId == 0 || cityId == '' || cityId == null)) {
            // $('#addCityDiv').append('<span class="cityprice" value=0-0 style="display: inline-block;width: auto;border: 1px solid #ccc;border-radius: 10px;padding: 5px 20px; margin-right: 5px;tmargin-bottom: 5px;background-color: #009688;color:#fff;">' + '全国' + ' <i style="font-style: normal;margin-left: 10px;cursor: pointer;">X</i></span>');
            layer.alert("请选择省份！");
        } else if (cityId == 0 || cityId == '' || cityId == null) {
            addCityDiv.append('<span class="cityprice" value=' + provinceId + '&' + ' style="display: inline-block;width: auto;border: 1px solid #ccc;border-radius: 10px;padding: 5px 20px; margin-right: 5px;tmargin-bottom: 5px;background-color: #009688;color:#fff;">' + provinceName + closeBtn + '</span>');
        } else {
            addCityDiv.append('<span class="cityprice" value=' + provinceId + '&' + cityId + ' style="display: inline-block;width: auto;border: 1px solid #ccc;border-radius: 10px;padding: 5px 20px; margin-right: 5px;tmargin-bottom: 5px;background-color: #009688;color:#fff;">' + cityName + closeBtn + '</span>');
        }
    }

    $('#addCityDiv').on('click', 'span i', function () {
        $(this).parent().remove();
        return false;
    });

    $('#addCityDiv1').on('click', 'span i', function () {
        $(this).parent().remove();
        return false;
    });

    let radio = false;
    let clickClose = false;
    if (json.channelPriceVO.channelPriceId !== null) {
        radio = true;
        clickClose = true;
    }
    if (json.channelPriceVO.channelId !== null) {

        json.channelList.forEach(function (item) {
            if (item.channelId === json.channelPriceVO.channelId) {
                item.selected = true;
            }
        })
    }
    let channelId = xmSelect.render({
        el: '#channelIds',
        name: 'channelIds',
        autoRow: false,
        tips: "-请选择",
        radio: radio,
        clickClose: clickClose,
        filterable: true,
        layVerify: 'required',
        layVerType: 'msg',
        layReqText: '渠道不能为空',
        prop: {
            value: 'channelId'
        },
        model: {
            label: {
                type: 'block',
                block: {
                    //最大显示数量, 0:不限制
                    showCount: 6,
                    //是否显示删除图标
                    showIcon: true,
                }
            }
        },
        data: json.channelList
    });

    let ajaxIndex;
    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {

        let data = obj.field;

        if (json.channelPriceVO.type == 1) {
            if (data.payType === null || data.payType === undefined) {
                layer.msg("选择支付方式!", {"icon": 2});
                return false;
            }
        }

        let channelPriceCityId = [];
        $('#addCityDiv').children("span").each(function (index, obj) {
            channelPriceCityId.push($(obj).attr('value'));
        });

        let channelBaseCityId = [];
        $('#addCityDiv1').children("span").each(function (index, obj) {
            channelBaseCityId.push($(obj).attr('value'));
        });

        if (channelPriceCityId.length == 0 && channelBaseCityId.length == 0) {
            layer.msg("至少选择一个城市!", {"icon": 2});
            return false;
        }
        if (data.type == 1 && !data.payType) {
            layer.msg("请设置支付方式!", {"icon": 2});
            return false;
        }
        if (data.payType == 1 && !data.depositStatus) {
            layer.msg("请设置是否设置定金!", {"icon": 2});
            return false;
        }

        // "下单时必须支付"，“设置定金”，定金必填
        if (data.payType == 1 && data.depositStatus != 1 && data.depositStatus != 2){
            layer.msg("请选择设置定金选项!", {"icon": 2});
            return false;
        }

        // "下单时必须支付"，“设置定金”，定金必填
        if (data.payType == 1 && data.depositStatus == 2) {
            if (!data.deposit || data.deposit == '') {
                layer.msg("请设置定金!", {"icon": 2});
                return false;
            }
            // data.deposit = data.deposit >= 100 ? data.deposit : data.deposit * 100
            data.deposit = data.deposit * 100
        } else {
            data.deposit = null;
            data.depositStatus = 1
        }

        if (data.payType == 1 && data.depositStatus == 2 && data.depositDeductionStatus != 1 && data.depositDeductionStatus != 2){
            layer.msg("请选择设置定金抵扣选项!", {"icon": 2});
            return false;
        }
        // "下单时必须支付"，“设置定金”，定金必填
        if (data.payType == 1 && data.depositStatus == 2 && data.depositDeductionStatus == 2) {
            if (!data.depositDeductionAmount || data.depositDeductionAmount == '') {
                layer.msg("请设置定金抵扣金额!", {"icon": 2});
                return false;
            }
            if (!/^[0-9]+(.[0-9]{1,2})?$/.test(data.depositDeductionAmount)) {
                layer.msg("定金抵扣金额必须为数字，支持两位小数!", {"icon": 2});
                return false;
            }
            let deposit = data.deposit / 100;
            if (data.depositDeductionAmount <= deposit) {
                layer.msg("定金抵扣金额必须需在" + deposit + " ~ " + (deposit * 10) + "之间!", {"icon": 2});
                return false;
            }
            if (data.depositDeductionAmount > deposit * 10){
                layer.msg("定金抵扣金额必须需在" + deposit + " ~ " + (deposit * 10) + "之间!", {"icon": 2});
                return false;
            }
            data.depositDeductionAmount = data.depositDeductionAmount * 100

        } else {
            data.depositDeductionAmount = null;
            data.depositDeductionStatus = 1
        }

        console.log(data);
        // 执行一口价城市
        data.channelPriceCityId = channelPriceCityId.join(",");
        // 执行标准价城市
        data.channelBaseCityId = channelBaseCityId.join(",");
        let url = "/pilot/channel/price/addEdit.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(data),
            beforeSend: function () {
                ajaxIndex = layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            success: function (res) {
                if (res.status == 200) {
                    layer.close(ajaxIndex);
                    if (json.channelPriceVO.channelPriceId != null && json.channelPriceVO.channelPriceId > 0) {
                        layer.msg("修改成功", {"icon": 1});
                        return false;
                    }
                    location.href = '/pilot/channel/price/serviceCategory.action?type=1&showType=2&configId=' + res.data;
                } else {
                    layer.msg("保存失败", {"icon": 2});
                }
            }
        });
        layer.close(ajaxIndex);
        return false;
    });

    form.on("select(channelId)", function (obj) {
        $('#addCityDiv').empty();
        $('#addCityDiv1').empty();
    });

    form.on('radio(depositStatus)', function (data) {
        if (data.value == 2) {
            $("#depositBlock").show();
            status = true;
        } else {
            $("#depositBlock").hide();
            status = false;
        }
    });
    form.on('radio(depositDeductionStatus)', function (data) {
        if (data.value == 2) {
            $("#depositDeductionAmountBlock").show();
        } else {
            $("#depositDeductionAmountBlock").hide();
        }
    });

    form.on('radio(payType)', function (data) {
        if (data.value == 1) {
            $("#setDeposit").show();
            status = true;
        } else {
            $("#setDeposit").hide();
            status = false;
        }
    });

    //对外暴露的接口
    exports('channel_price_edit_js', {});
});